import PySimpleGUI as sg

"""
将每个Checkbox与对应的卸载Button放入单独的sg.Column以实现更好的布局效果。
为“一键卸载”功能增加确认对话框，防止用户误操作导致所有选中的应用被卸载。
"""


def uninstall(app_name):
    sg.popup(f'卸载 {app_name}')


sg.theme('SystemDefaultForReal')
app_list = ['App1', 'App2', 'App3', 'App4', 'App5', 'App6', 'App7', 'App8', 'App9', 'App10', 'App11', 'App12', 'App13',
            'App14', 'App15', 'App16', 'App17', 'App18', 'App19', 'App20']
row_cap = 4 if len(app_list) > 24 else 3
frame_layout = []
row_layout = []
for index, app in enumerate(app_list):
    if index % row_cap == 0:
        row_layout = []

    column_layout = [[
        sg.Checkbox(app, size=(23, 1), key=app),
        sg.Button('卸载', key=f'button-{app}')
    ]]
    row_layout.append(sg.Column(column_layout))
    if len(row_layout) == row_cap or index == len(app_list) - 1:
        frame_layout.append(row_layout)
layout = [
    [sg.Frame('应用列表', frame_layout)],
    [
        sg.Button('全选'),
        sg.Button('反选'),
        sg.Button('全不选'),
        sg.Button('一键卸载'),
    ]
]

window = sg.Window('Frame Test', layout)

while True:
    event, values = window.read()
    if event in (sg.WINDOW_CLOSED, 'Cancel'):
        break
    if event.startswith('button-'):
        app_name = event.split('-')[1]
        uninstall(app_name)

    if event == '全选':
        for app in app_list:
            window[f'{app}'].update(True)
    elif event == '反选':
        for app in app_list:
            window[app].update(not window[app].get())
    elif event == '全不选':
        for app in app_list:
            window[app].update(False)
    elif event == '一键卸载':
        selected_apps = [app for app in app_list if window[app].get()]
        if sg.popup_yes_no(f'确定要卸载选中的{len(selected_apps)}个应用吗?') == 'Yes':
            for app in selected_apps:
                uninstall(app)
window.close()
